/*
 * @Description: 登录页   Login
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-09-02 09:08:37
 * @LastAuthor: zhengzhuang
 * @lastTime: 2019-12-11 11:38:03
 */
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/MyDialog.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../utils/permission_handler.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final TextEditingController _controller = new TextEditingController();
  final TextEditingController _controlleT = new TextEditingController();
  Timer _timer;
  int _countdownTime = 0;
  var btnText = "获取验证码";
  String cellPhoneNumber; // 用户输入手机号
  DateTime lastPopTime; // 连续点击两次退出APP时间
  bool _checkboxSelected = false; // 隐私协议
  String isAgree = '';
  @override
  void initState() {
    super.initState();

    /// 获取定位 华为要求 您的应用在用户拒绝“位置”权限后，存在重新运行时弹窗申请权限问题 申请权限注释掉
    // PermissionHandlerX.position(context);

  }

  _getIsAgree() async {
    var sp = await SharedPreferences.getInstance();
    isAgree = sp.getString("isAgree");
    if (isAgree == "" || isAgree == null) {
      _openAlertDialog(context);
    }
  }

  /// 退出登录当前账号
  Future _openAlertDialog(context) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return WillPopScope(
            child: Material(
              type: MaterialType.transparency,
              child: Container(
                margin: EdgeInsets.all(ScreenUtil().setWidth(48.0)),
                decoration: BoxDecoration(
                  borderRadius:
                      BorderRadius.circular(ScreenUtil().setWidth(20.0)),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      color: Colors.white,
                      child: Column(
                        children: <Widget>[
                          SizedBox(height: ScreenUtil().setWidth(20.0)),
                          Padding(
                            padding: EdgeInsets.only(top: 8),
                            child: Text('温馨提示',
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(30.0),
                                    color: Color.fromARGB(255, 51, 51, 51),
                                    fontWeight: FontWeight.w500,
                                    decoration: TextDecoration.none)),
                          ),
                          SizedBox(height: ScreenUtil().setWidth(30.0)),
                          Container(
                            width: ScreenUtil().setWidth(600.0),
                            child: Column(
                              children: [
                                Text(
                                  '亲爱的用户，感谢您对C20出行一直以来的信任！',
                                  textAlign: TextAlign.justify,
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(28.0),
                                    color: Color.fromARGB(255, 102, 102, 102),
                                  ),
                                ),
                                RichText(
                                  text: TextSpan(
                                      text: "我们依据最新的监管要求更新了C20出行的",
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(28.0),
                                        color:
                                            Color.fromARGB(255, 102, 102, 102),
                                      ),
                                      children: <TextSpan>[
                                        TextSpan(
                                          text: "《隐私政策》",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color(0xff3FB956),
                                          ),
                                          recognizer: TapGestureRecognizer()
                                            ..onTap = () =>
                                                NavigatorUtil.jumpWebView(
                                                    context,
                                                    'http://c20h5.huashichuxing.com/yinsizhengce'),
                                        ),
                                        TextSpan(
                                          text: "和",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color.fromARGB(
                                                255, 102, 102, 102),
                                          ),
                                        ),
                                        TextSpan(
                                          text: "《用户协议》",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color(0xff3FB956),
                                          ),
                                          recognizer: TapGestureRecognizer()
                                            ..onTap = () =>
                                                NavigatorUtil.jumpWebView(
                                                    context,
                                                    'http://c20h5.huashichuxing.com/serviceAgreement'),
                                        ),
                                        TextSpan(
                                          text: "特向您说明，详情请点击阅读。",
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(28.0),
                                            color: Color.fromARGB(
                                                255, 102, 102, 102),
                                          ),
                                        ),
                                      ]),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: ScreenUtil().setWidth(30.0)),
                          Container(
                              // padding: EdgeInsets.only(top: 15, bottom: 8),
                              decoration: BoxDecoration(
                                  border: Border(
                                      top: BorderSide(
                                          width: ScreenUtil().setWidth(1.0),
                                          color: Colors.black12))),
                              child: Row(
                                children: [
                                  FlatButton(
                                      minWidth: ScreenUtil().setWidth(326.0),
                                      height: ScreenUtil().setWidth(100.0),
                                      onPressed: () async {
                                        ToastX.center("请同意条款后使用c20出行服务");
                                        // 关闭 Dialog
                                      },
                                      child: Text('不同意',
                                          style: TextStyle(
                                              color: Color.fromARGB(
                                                  255, 153, 153, 153),
                                              fontSize:
                                                  ScreenUtil().setSp(30.0)))),
                                  SizedBox(
                                    width: ScreenUtil().setWidth(2.0),
                                    height: ScreenUtil().setWidth(100.0),
                                    child: DecoratedBox(
                                      decoration:
                                          BoxDecoration(color: Colors.black12),
                                    ),
                                  ),
                                  FlatButton(
                                      minWidth: ScreenUtil().setWidth(326.0),
                                      height: ScreenUtil().setWidth(100.0),
                                      onPressed: () async {
                                        var sp = await SharedPreferences
                                            .getInstance();
                                        sp.setString("isAgree", "agree");
                                        Navigator.pop(context, 'cancel');
                                      },
                                      child: Text('同意',
                                          style: TextStyle(
                                              color: Color(0xff3FB956),
                                              fontSize:
                                                  ScreenUtil().setSp(30.0)))),
                                ],
                              ))
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            onWillPop: () async => false);
      },
    );
  }

  // 30秒倒计时
  void startCountdownTimer() {
    _countdownTime = 30;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownTime < 1) {
          _timer.cancel();
          btnText = '点击重新获取';
        } else {
          _countdownTime = _countdownTime - 1;
          btnText = '${this._countdownTime}秒后点击重新获取';
        }
      });
    });
  }

  // 验证码
  _sendVerificationCode() {
    if (_controller.text == null || _controller.text == '')
      return ToastX.center('请输入手机号');
    RegExp reg = new RegExp(r'^\d{11}$');
    if (!reg.hasMatch(_controller.text)) return ToastX.center('请输入11位手机号码');
    // 触摸空白处收起键盘
    FocusScope.of(context).requestFocus(FocusNode());
    // MyDialog.loadDialog(context: context);
    Request.sendVerificationCode(context, _controller.text);
    startCountdownTimer();
    print("3333");
  }

  // 点击注册或登录
  Future _signIn() async {
    if (!_checkboxSelected) return ToastX.center("请先阅读隐私协议");
    if (_controlleT.text == null || _controlleT.text == '')
      return ToastX.center('请输入验证码');
    RegExp reg = new RegExp(r'^\d{4}$');
    if (!reg.hasMatch(_controlleT.text)) return ToastX.center('请输入正确验证码');
    // 触摸空白处收起键盘
    FocusScope.of(context).requestFocus(FocusNode());
    MyDialog.loadDialog(context: context);
    Request.codeLogin(context, _controller.text, _controlleT.text);
  }

  @override
  Widget build(BuildContext context) {
    // 设置适配尺寸 (填入设计稿中设备的屏幕尺寸) 此处假如设计稿是按iPhone6的尺寸设计的(iPhone6 750*1334)
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
    // 显示顶部状态栏, 显示例如华为等产片的底部虚拟按键
    SystemChrome.setEnabledSystemUIOverlays(
        [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    return WillPopScope(
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          // 触摸空白处收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: AppBar(
            brightness: Brightness.light,
            backgroundColor: Colors.white,
            automaticallyImplyLeading: false,
            elevation: 0.0,
          ),
          backgroundColor: Colors.white,
          body: SafeArea(
            child: Container(
              width: ScreenUtil().setWidth(750.0),
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(40.0),
                right: ScreenUtil().setWidth(40.0),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(height: ScreenUtil().setWidth(200.0)),
                  Row(
                    children: [
                      Image.asset(
                        "assets/icon/logoin.png",
                        width: ScreenUtil().setWidth(96),
                        height: ScreenUtil().setWidth(96),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 10),
                        child: Text(
                          '欢迎加入C20出行',
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(40.0),
                              color: Color(0xff333333),
                              fontWeight: FontWeight.w500),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: ScreenUtil().setWidth(80.0)),
                  Container(
                    width: ScreenUtil().setWidth(650.0),
                    padding: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                    child: TextField(
                      controller: _controller,
                      keyboardType: TextInputType.number,
                      toolbarOptions: ToolbarOptions(copy: false,cut: false,paste: false,selectAll: false),
                      decoration: InputDecoration(
                        hintText: '请输入常用手机号',
                        hintStyle: TextStyle(
                          color: Colors.grey,
                          fontSize: ScreenUtil().setSp(40.0),
                        ),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xffEEEEEE), //边框颜色为绿色
                            width: 1, //宽度为5
                          ),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xffEEEEEE), //边框颜色为绿色
                            width: 1, //宽度为5
                          ),
                        ),
                      ),
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: ScreenUtil().setSp(40.0),
                      ),
                    ),
                  ),
                  SizedBox(height: ScreenUtil().setWidth(80.0)),
                  Container(
                    width: ScreenUtil().setWidth(650.0),
                    padding: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                    child: TextField(
                      controller: _controlleT,
                      keyboardType: TextInputType.number,
                      toolbarOptions: ToolbarOptions(copy: false,cut: false,paste: false,selectAll: false),
                      decoration: InputDecoration(
                        hintText: '请输入验证码',
                        hintStyle: TextStyle(
                          color: Colors.grey,
                          fontSize: ScreenUtil().setSp(40.0),
                        ),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xffEEEEEE), //边框颜色为绿色
                            width: 1, //宽度为5
                          ),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: Color(0xffEEEEEE), //边框颜色为绿色
                            width: 1, //宽度为5
                          ),
                        ),
                        suffixIcon: FlatButton(
                          child: Text(
                            "${this.btnText}",
                            style: TextStyle(
                                color: Color(0xff3FB956),
                                fontSize: ScreenUtil().setSp(28)),
                          ),
                          onPressed: () {
                            print(_countdownTime);
                            if (_countdownTime > 0) {
                              print("111111");
                              ToastX.center('请稍后');
                            } else {
                              print("2222");
                              _sendVerificationCode();
                            }
                          },
                        ),
                      ),
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: ScreenUtil().setSp(40.0),
                      ),
                    ),
                  ),
                  SizedBox(height: ScreenUtil().setWidth(80.0)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Checkbox(
                          value: _checkboxSelected,
                          activeColor: Color(0xff3FB956),
                          onChanged: (value) {
                            setState(() {
                              _checkboxSelected = value;
                            });
                          }),
                      Text(
                        '同意',
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(24.0),
                          color: Color.fromARGB(255, 153, 153, 153),
                        ),
                      ),
                      InkWell(
                        child: Text(
                          '《用户协议》',
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(24.0),
                            color: Color(0xff3FB956),
                          ),
                        ),
                        onTap: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          NavigatorUtil.jumpWebView(context,
                              "http://c20h5.huashichuxing.com/serviceAgreement");
                        },
                      ),
                      Text(
                        '和',
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(24.0),
                          color: Color.fromARGB(255, 153, 153, 153),
                        ),
                      ),
                      InkWell(
                        child: Text(
                          '《隐私政策》',
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(24.0),
                            color: Color(0xff3FB956),
                          ),
                        ),
                        onTap: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          NavigatorUtil.jumpWebView(context,
                              "http://c20h5.huashichuxing.com/yinsizhengce");
                        },
                      ),
                    ],
                  ),
                  SizedBox(height: ScreenUtil().setWidth(54.0)),
                  Container(
                    width: ScreenUtil().setWidth(650.0),
                    height: ScreenUtil().setWidth(100.0),
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                          colors: [Color(0xff3FB956), Color(0xff65CA00)],
                        ),
                        borderRadius: BorderRadius.all(
                            Radius.circular(ScreenUtil().setWidth(50)))),
                    child: MaterialButton(
                      textColor: Colors.white,
                      child: Text(
                        '登录',
                        style: TextStyle(
                            color: Color(0xffffffff),
                            fontSize: ScreenUtil().setWidth(32),
                            fontWeight: FontWeight.w500),
                      ),
                      onPressed: () {
                        _signIn();
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      onWillPop: () async {
        // 点击返回键的操作
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
          lastPopTime = DateTime.now();
          ToastX.bottom('再按一次退出应用');
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          return await SystemChannels.platform
              .invokeMethod('SystemNavigator.pop');
        }
      },
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    _controlleT.dispose();
    super.dispose();
  }
}
